<template>
  <div class="main-content-wrapper">
    <!-- 顶部统计卡片 -->
    <div class="stats-cards">
      <div class="stats-card stats-card-blue">
        <div class="stats-content">
          <div class="stats-title">销售总额</div>
          <div class="stats-value">{{ formatCurrency(statistics.totalRevenue) }}</div>
        </div>
        <div class="stats-icon">💰</div>
      </div>
      <div class="stats-card stats-card-green">
        <div class="stats-content">
          <div class="stats-title">已收总额</div>
          <div class="stats-value">{{ formatCurrency(statistics.receivedAmount) }}</div>
        </div>
        <div class="stats-icon">📊</div>
      </div>
      <div class="stats-card stats-card-blue-2">
        <div class="stats-content">
          <div class="stats-title">待收总额</div>
          <div class="stats-value">{{ formatCurrency(statistics.pendingAmount) }}</div>
        </div>
        <div class="stats-icon">📋</div>
      </div>
      <div class="stats-card stats-card-red">
        <div class="stats-content">
          <div class="stats-title">采购总额</div>
          <div class="stats-value">{{ formatCurrency(statistics.totalPurchaseAmount) }}</div>
        </div>
        <div class="stats-icon">🚚</div>
      </div>
      <div class="stats-card stats-card-yellow">
        <div class="stats-content">
          <div class="stats-title">库存总数量</div>
          <div class="stats-value">{{ (statistics.inventoryQuantity || 0).toLocaleString() }}</div>
        </div>
        <div class="stats-icon">📦</div>
      </div>
      <div class="stats-card stats-card-purple">
        <div class="stats-content">
          <div class="stats-title">库存总额</div>
          <div class="stats-value">{{ formatCurrency(statistics.inventoryAmount) }}</div>
        </div>
        <div class="stats-icon">👤</div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <div class="chart-row">
        <div class="chart-container large-chart">
          <div class="chart-header">
            <h3>销售趋势分析</h3>
            <div class="chart-legend">
              <div class="legend-item">
                <div class="legend-color" style="background: #667EEA;"></div>
                <span style="font-size: 11px; color: #64748B; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">销售额</span>
              </div>
              <div class="legend-item">
                <div class="legend-color" style="background: #F093FB;"></div>
                <span style="font-size: 11px; color: #64748B; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">毛利率</span>
              </div>
            </div>
          </div>
          <div class="chart-content">
            <canvas ref="salesChart" width="600" height="240"></canvas>
          </div>
        </div>
        <div class="chart-container small-chart">
          <div class="chart-header">
            <h3>订单销售额分布</h3>
          </div>
          <div class="chart-content">
            <canvas ref="orderDistributionChart" width="200" height="200"></canvas>
          </div>
        </div>
      </div>
      <div class="chart-row">
        <div class="chart-container medium-chart">
          <div class="chart-header">
            <h3>采购商品金额趋势</h3>
            <div class="chart-legend">
              <div class="legend-item">
                <div class="legend-color" style="background: #4ECDC4;"></div>
                <span style="font-size: 11px; color: #64748B; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">采购金额</span>
              </div>
              <div class="legend-item">
                <div class="legend-color" style="background: #96CEB4;"></div>
                <span style="font-size: 11px; color: #64748B; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">采购数量</span>
              </div>
            </div>
          </div>
          <div class="chart-content">
            <canvas ref="procurementChart" width="400" height="180"></canvas>
          </div>
        </div>
        <div class="chart-container medium-chart">
          <div class="chart-header">
            <h3>生产不合格率趋势</h3>
            <div class="chart-legend">
              <div class="legend-item">
                <div class="legend-color" style="background: #FF6B6B;"></div>
                <span style="font-size: 11px; color: #64748B; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">不合格数量</span>
              </div>
            </div>
          </div>
          <div class="chart-content">
            <canvas ref="qualityChart" width="400" height="180"></canvas>
          </div>
        </div>
        <div class="chart-container stats-table">
          <div class="chart-header">
            <h3>数据统计</h3>
          </div>
          <div class="stats-list">
            <div class="stats-row">
              <span class="stats-label">订单总数</span>
              <span class="stats-number">{{ (statistics.totalOrders || 0).toLocaleString() }}</span>
              <span class="stats-percent">{{ statistics.orderGrowth || 0 }}%</span>
            </div>
            <div class="stats-row">
              <span class="stats-label">客户数量</span>
              <span class="stats-number">{{ (statistics.totalCustomers || 0).toLocaleString() }}</span>
              <span class="stats-percent">{{ statistics.customerGrowth || 0 }}%</span>
            </div>
            <div class="stats-row">
              <span class="stats-label">商品数量</span>
              <span class="stats-number">{{ (statistics.totalProducts || 0).toLocaleString() }}</span>
              <span class="stats-percent">{{ statistics.productGrowth || 0 }}%</span>
            </div>
            <div class="stats-row">
              <span class="stats-label">发货数量</span>
              <span class="stats-number">{{ (statistics.deliveredQuantity || 0).toLocaleString() }}</span>
              <span class="stats-percent">{{ statistics.purchaseGrowth || 0 }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 销售订单表格 -->
    <div class="table-section">
      <div class="table-header">
        <h3>销售订单</h3>
        <div class="table-controls">
          <select class="table-select"><option>关键词</option></select>
          <input type="text" placeholder="请输入关键词搜索" class="table-search">
          <select class="table-select"><option>订单状态</option></select>
          <select class="table-select"><option>全部</option></select>
          <select class="table-select"><option>期望发货时间</option></select>
          <input type="text" placeholder="请选择时间范围" class="table-search">
          <button class="search-btn">搜索</button>
          <button class="reset-btn">重置</button>
        </div>
      </div>
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>序号</th>
              <th>销售订单号</th>
              <th>成单时间</th>
              <th>期望发货时间</th>
              <th>订单商品数</th>
              <th>待发货数量</th>
              <th>已发货数量</th>
              <th>订单总额</th>
              <th>应收总额</th>
              <th>已收总额</th>
              <th>待收总额</th>
              <th>已退总额</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="latestOrders.length === 0">
              <td colspan="12" style="text-align: center; color: #999;">暂无订单数据</td>
            </tr>
            <tr v-for="(order, index) in latestOrders" :key="order.orderId || index">
              <td>{{ index + 1 }}</td>
              <td>{{ order.orderNumber || '-' }}</td>
              <td>{{ order.orderDate || '-' }}</td>
              <td>{{ order.expectedDeliveryDate || '-' }}</td>
              <td>{{ order.productCount || 0 }}</td>
              <td>{{ order.pendingQuantity || 0 }}</td>
              <td>{{ order.shippedQuantity || 0 }}</td>
              <td>{{ formatCurrency(order.orderAmount) }}</td>
              <td>{{ formatCurrency(order.receivables) }}</td>
              <td>{{ formatCurrency(order.amountReceived) }}</td>
              <td>{{ formatCurrency(order.amountCollected) }}</td>
              <td>{{ formatCurrency(order.refundedTotal) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="table-pagination">
        <div class="pagination-info">
          <span>共 {{ pagination.total }} 条记录，每页 {{ pagination.pageSize }} 条</span>
        </div>
        <div class="pagination-controls">
          <button 
            class="page-btn" 
            :class="{ disabled: pagination.currentPage === 1 }"
            @click="changePage(pagination.currentPage - 1)"
            :disabled="pagination.currentPage === 1">
            上一页
          </button>
          
          <button 
            v-for="page in getVisiblePages()" 
            :key="page"
            class="page-btn" 
            :class="{ active: page === pagination.currentPage }"
            @click="changePage(page)">
            {{ page }}
          </button>
          
          <span v-if="pagination.totalPages > 7 && pagination.currentPage < pagination.totalPages - 3">...</span>
          
          <button 
            class="page-btn" 
            :class="{ disabled: pagination.currentPage === pagination.totalPages }"
            @click="changePage(pagination.currentPage + 1)"
            :disabled="pagination.currentPage === pagination.totalPages">
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import http from '@/api/http'

export default {
  name: 'DashboardContent',
  data() {
    return {
      statistics: {
        totalRevenue: 0,
        receivedAmount: 0,
        pendingAmount: 0,
        totalPurchaseAmount: 0,
        inventoryQuantity: 0,
        inventoryAmount: 0
      },
      salesTrend: [],
      procurementTrend: [],
      qualityTrend: [],
      orderDistribution: [],
      latestOrders: [],
      // 分页相关数据
      pagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
        totalPages: 0
      }
    }
  },
  mounted() {
    this.loadDashboardData();
  },
  methods: {
    async loadDashboardData() {
      try {
        await Promise.all([
          this.loadStatistics(),
          this.loadSalesTrend(),
          this.loadProcurementTrend(),
          this.loadQualityTrend(),
          this.loadOrderDistribution(),
          this.loadLatestOrders()
        ]);
        this.initCharts();
      } catch (error) {
        console.error('加载看板数据失败:', error);
      }
    },
    async loadStatistics() {
      try {
        const response = await http.get('/intelligent-workbench/dashboard/statistics');
        console.log('统计数据响应:', response.data);
        this.statistics = response.data.data || {};
        console.log('统计数据已加载:', this.statistics);
      } catch (error) {
        console.error('加载统计数据失败:', error);
      }
    },
    async loadSalesTrend() {
      try {
        const response = await http.get('/intelligent-workbench/dashboard/sales-trend');
        console.log('销售趋势数据响应:', response.data);
        this.salesTrend = response.data.data || [];
        console.log('销售趋势数据已加载:', this.salesTrend);
      } catch (error) {
        console.error('加载销售趋势数据失败:', error);
      }
    },
    async loadProcurementTrend() {
      try {
        const response = await http.get('/intelligent-workbench/dashboard/procurement-trend');
        console.log('采购趋势数据响应:', response.data);
        this.procurementTrend = response.data.data || [];
        console.log('采购趋势数据已加载:', this.procurementTrend);
      } catch (error) {
        console.error('加载采购趋势数据失败:', error);
      }
    },
    async loadQualityTrend() {
      try {
        const response = await http.get('/intelligent-workbench/dashboard/production-quality-trend');
        console.log('质量趋势数据响应:', response.data);
        this.qualityTrend = response.data.data || [];
        console.log('质量趋势数据已加载:', this.qualityTrend);
      } catch (error) {
        console.error('加载生产合格率数据失败:', error);
        // 使用模拟数据
        this.qualityTrend = [
          { month: '1月', qualityRate: 96.5 },
          { month: '2月', qualityRate: 97.2 },
          { month: '3月', qualityRate: 98.1 },
          { month: '4月', qualityRate: 97.8 },
          { month: '5月', qualityRate: 98.5 },
          { month: '6月', qualityRate: 98.9 }
        ];
        console.log('使用模拟质量趋势数据:', this.qualityTrend);
      }
    },
    async loadOrderDistribution() {
      try {
        const response = await http.get('/intelligent-workbench/dashboard/order-distribution');
        console.log('订单分布数据响应:', response.data);
        this.orderDistribution = response.data.data || [];
        console.log('订单分布数据已加载:', this.orderDistribution);
      } catch (error) {
        console.error('加载订单分布数据失败:', error);
      }
    },
    async loadLatestOrders() {
      try {
        const params = {
          page: this.pagination.currentPage,
          limit: this.pagination.pageSize
        };
        const response = await http.get('/intelligent-workbench/dashboard/latest-orders', { params });
        console.log('最新订单数据响应:', response.data);
        
        if (response.data && response.data.code === 200) {
          // 后端返回的数据结构: {code: 200, msg: "操作成功", data: {data: [...], total: ..., page: ..., limit: ..., totalPages: ...}}
          const responseData = response.data.data;
          this.latestOrders = responseData.data || [];
          // 更新分页信息
          this.pagination.total = responseData.total || 0;
          this.pagination.totalPages = responseData.totalPages || Math.ceil(this.pagination.total / this.pagination.pageSize);
        } else {
          this.latestOrders = [];
          this.pagination.total = 0;
          this.pagination.totalPages = 0;
        }
        
        console.log('最新订单数据已加载:', this.latestOrders);
        console.log('分页信息:', this.pagination);
      } catch (error) {
        console.error('加载最新订单数据失败:', error);
        this.latestOrders = [];
        this.pagination.total = 0;
        this.pagination.totalPages = 0;
      }
    },
    formatCurrency(value) {
      if (value === null || value === undefined || isNaN(value)) {
        return '¥0.00';
      }
      return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2
      }).format(value);
    },
    getOrderStatusText(status) {
      const statusMap = {
        0: { text: '已发货', class: 'status-red' },
        1: { text: '已完成', class: 'status-gray' },
        2: { text: '部分发货', class: 'status-orange' },
        3: { text: '待发货', class: 'status-green' }
      };
      return statusMap[status] || { text: '未知', class: 'status-gray' };
    },
    getStatusClass(status) {
      const statusClassMap = {
        '待发货': 'status-pending',
        '部分发货': 'status-partial',
        '已发货': 'status-shipped',
        '已完成': 'status-completed'
      };
      return statusClassMap[status] || 'status-default';
    },
    // 分页相关方法
    changePage(page) {
      if (page < 1 || page > this.pagination.totalPages || page === this.pagination.currentPage) {
        return;
      }
      this.pagination.currentPage = page;
      this.loadLatestOrders();
    },
    getVisiblePages() {
      const current = this.pagination.currentPage;
      const total = this.pagination.totalPages;
      const pages = [];
      
      if (total <= 7) {
        // 如果总页数小于等于7，显示所有页码
        for (let i = 1; i <= total; i++) {
          pages.push(i);
        }
      } else {
        // 如果总页数大于7，智能显示页码
        if (current <= 4) {
          // 当前页在前4页
          for (let i = 1; i <= 5; i++) {
            pages.push(i);
          }
          pages.push(total);
        } else if (current >= total - 3) {
          // 当前页在后4页
          pages.push(1);
          for (let i = total - 4; i <= total; i++) {
            pages.push(i);
          }
        } else {
          // 当前页在中间
          pages.push(1);
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i);
          }
          pages.push(total);
        }
      }
      
      return pages;
    },
    initCharts() {
      this.drawSalesChart();
      this.drawOrderDistributionChart();
      this.drawProcurementChart();
      this.drawQualityChart();
    },
    drawSalesChart() {
      const canvas = this.$refs.salesChart;
      if (!canvas) return;
      const ctx = canvas.getContext('2d');
      const width = canvas.width;
      const height = canvas.height;
      
      ctx.clearRect(0, 0, width, height);
      
      if (!this.salesTrend || this.salesTrend.length === 0) {
        ctx.fillStyle = '#94A3B8';
        ctx.font = '16px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText('暂无数据', width / 2, height / 2);
        return;
      }
      
      console.log('绘制销售趋势图表，数据:', this.salesTrend);
      
      // 设置图表边距
      const margin = { top: 20, right: 30, bottom: 40, left: 60 };
      const chartWidth = width - margin.left - margin.right;
      const chartHeight = height - margin.top - margin.bottom;
      
      // 处理数据格式
      console.log('销售趋势原始数据:', this.salesTrend);
      const salesData = Array.isArray(this.salesTrend) ? this.salesTrend.map(item => item.amount || 0) : (this.salesTrend.salesData || []);
      const months = Array.isArray(this.salesTrend) ? this.salesTrend.map(item => item.month || '') : (this.salesTrend.months || []);
      const profitRates = salesData.map(() => Math.random() * 20 + 10); // 模拟毛利率数据
      
      console.log('处理后的销售数据:', salesData);
      console.log('处理后的月份数据:', months);
      
      if (salesData.length === 0) {
        ctx.fillStyle = '#94A3B8';
        ctx.font = '16px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText('暂无数据', width / 2, height / 2);
        return;
      }
      
      // 获取最大值用于缩放
      const maxSales = Math.max(...salesData);
      const maxProfit = Math.max(...profitRates);
      
      // 绘制精致的网格线
      ctx.strokeStyle = '#F1F5F9';
      ctx.lineWidth = 1;
      for (let i = 0; i <= 4; i++) {
        const y = margin.top + (chartHeight / 4) * i;
        ctx.beginPath();
        ctx.moveTo(margin.left, y);
        ctx.lineTo(width - margin.right, y);
        ctx.stroke();
      }
      
      // 绘制Y轴标签 - 更优雅的样式
      for (let i = 0; i <= 4; i++) {
        const y = margin.top + (chartHeight / 4) * i;
        const value = Math.round((maxSales * (4 - i)) / 4 / 10000) + '万';
        ctx.fillStyle = '#64748B';
        ctx.font = '13px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
        ctx.textAlign = 'right';
        ctx.fillText(value, margin.left - 10, y + 4);
      }
      
      // 绘制销售额面积填充 - 更优雅的渐变
      const salesGradient = ctx.createLinearGradient(0, margin.top, 0, height - margin.bottom);
      salesGradient.addColorStop(0, 'rgba(79, 70, 229, 0.15)');
      salesGradient.addColorStop(0.6, 'rgba(79, 70, 229, 0.08)');
      salesGradient.addColorStop(1, 'rgba(79, 70, 229, 0.02)');
      
      ctx.fillStyle = salesGradient;
      ctx.beginPath();
      ctx.moveTo(margin.left, height - margin.bottom);
      salesData.forEach((value, index) => {
        const x = margin.left + (chartWidth / (salesData.length - 1)) * index;
        const y = height - margin.bottom - (value / maxSales) * chartHeight;
        ctx.lineTo(x, y);
      });
      ctx.lineTo(width - margin.right, height - margin.bottom);
      ctx.closePath();
      ctx.fill();
      
      // 绘制毛利率面积填充 - 更淡雅的颜色
      const profitGradient = ctx.createLinearGradient(0, margin.top, 0, height - margin.bottom);
      profitGradient.addColorStop(0, 'rgba(236, 72, 153, 0.12)');
      profitGradient.addColorStop(0.6, 'rgba(236, 72, 153, 0.06)');
      profitGradient.addColorStop(1, 'rgba(236, 72, 153, 0.01)');
      
      ctx.fillStyle = profitGradient;
      ctx.beginPath();
      ctx.moveTo(margin.left, height - margin.bottom);
      profitRates.forEach((rate, index) => {
        const x = margin.left + (chartWidth / (profitRates.length - 1)) * index;
        const y = height - margin.bottom - (rate / maxProfit) * chartHeight * 0.6;
        if (index === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
      });
      ctx.lineTo(width - margin.right, height - margin.bottom);
      ctx.closePath();
      ctx.fill();
      
      // 绘制销售额趋势线 - 更精致的样式
      ctx.strokeStyle = '#4F46E5';
      ctx.lineWidth = 3;
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
      ctx.beginPath();
      salesData.forEach((value, index) => {
        const x = margin.left + (chartWidth / (salesData.length - 1)) * index;
        const y = height - margin.bottom - (value / maxSales) * chartHeight;
        if (index === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
      });
      ctx.stroke();
      
      // 绘制毛利率趋势线 - 更精致的样式
      ctx.strokeStyle = '#EC4899';
      ctx.lineWidth = 2.5;
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
      ctx.beginPath();
      profitRates.forEach((rate, index) => {
        const x = margin.left + (chartWidth / (profitRates.length - 1)) * index;
        const y = height - margin.bottom - (rate / maxProfit) * chartHeight * 0.6;
        if (index === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
      });
      ctx.stroke();
      
      // 绘制销售额数据点 - 更精致的设计
      salesData.forEach((value, index) => {
        const x = margin.left + (chartWidth / (salesData.length - 1)) * index;
        const y = height - margin.bottom - (value / maxSales) * chartHeight;
        
        // 外圈
        ctx.fillStyle = '#FFFFFF';
        ctx.beginPath();
        ctx.arc(x, y, 5, 0, 2 * Math.PI);
        ctx.fill();
        
        // 内圈
        ctx.fillStyle = '#4F46E5';
        ctx.beginPath();
        ctx.arc(x, y, 3, 0, 2 * Math.PI);
        ctx.fill();
        
        // 边框
         ctx.strokeStyle = '#4F46E5';
         ctx.lineWidth = 2;
         ctx.beginPath();
         ctx.arc(x, y, 5, 0, 2 * Math.PI);
         ctx.stroke();
       });
       
       // 绘制毛利率数据点 - 更精致的设计
       profitRates.forEach((rate, index) => {
         const x = margin.left + (chartWidth / (profitRates.length - 1)) * index;
         const y = height - margin.bottom - (rate / maxProfit) * chartHeight * 0.6;
         
         // 外圈
         ctx.fillStyle = '#FFFFFF';
         ctx.beginPath();
         ctx.arc(x, y, 4, 0, 2 * Math.PI);
         ctx.fill();
         
         // 内圈
         ctx.fillStyle = '#EC4899';
         ctx.beginPath();
         ctx.arc(x, y, 2.5, 0, 2 * Math.PI);
         ctx.fill();
         
         // 边框
         ctx.strokeStyle = '#EC4899';
         ctx.lineWidth = 1.5;
         ctx.beginPath();
         ctx.arc(x, y, 4, 0, 2 * Math.PI);
         ctx.stroke();
       });
       
       // 绘制月份标签 - 更优雅的样式
       months.forEach((month, index) => {
         if (month) {
           const x = margin.left + (chartWidth / (months.length - 1)) * index;
           ctx.fillStyle = '#64748B';
           ctx.font = '12px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
           ctx.textAlign = 'center';
           ctx.fillText(month, x, height - margin.bottom + 20);
         }
       });
    },
    drawOrderDistributionChart() {
       const canvas = this.$refs.orderDistributionChart;
       if (!canvas) return;
       const ctx = canvas.getContext('2d');
       const centerX = canvas.width / 2;
       const centerY = canvas.height / 2;
       const radius = 80;
       
       ctx.clearRect(0, 0, canvas.width, canvas.height);
       
       if (!this.orderDistribution || this.orderDistribution.length === 0) {
         ctx.fillStyle = '#999';
         ctx.font = '14px Arial';
         ctx.textAlign = 'center';
         ctx.fillText('暂无数据', canvas.width / 2, canvas.height / 2);
         return;
       }
       
       console.log('绘制订单分布图表，数据:', this.orderDistribution);
       
       const total = this.orderDistribution.reduce((sum, item) => sum + item.amount, 0);
       const colors = ['#667EEA', '#F093FB', '#4ECDC4', '#45B7D1', '#96CEB4'];
       
       let currentAngle = -Math.PI / 2;
       
       this.orderDistribution.forEach((item, index) => {
         const sliceAngle = (item.amount / total) * 2 * Math.PI;
         
         ctx.beginPath();
         ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle);
         ctx.lineTo(centerX, centerY);
         ctx.fillStyle = colors[index % colors.length];
         ctx.fill();
         
         currentAngle += sliceAngle;
       });
       
       // 绘制中心圆
       ctx.beginPath();
       ctx.arc(centerX, centerY, radius - 30, 0, 2 * Math.PI);
       ctx.fillStyle = 'white';
       ctx.fill();
       
       // 绘制总金额
       ctx.fillStyle = '#333';
       ctx.font = 'bold 16px Arial';
       ctx.textAlign = 'center';
       ctx.fillText('总销售额', centerX, centerY - 5);
       ctx.font = '12px Arial';
       ctx.fillText(this.formatCurrency(total), centerX, centerY + 15);
     },
    drawProcurementChart() {
       const canvas = this.$refs.procurementChart;
       if (!canvas) return;
       const ctx = canvas.getContext('2d');
       const width = canvas.width;
       const height = canvas.height;
       
       ctx.clearRect(0, 0, width, height);
       
       console.log('绘制采购趋势图表，数据:', this.procurementTrend);
       
       // 设置图表边距
       const margin = { top: 20, right: 30, bottom: 40, left: 60 };
       const chartWidth = width - margin.left - margin.right;
       const chartHeight = height - margin.top - margin.bottom;
       
       // 处理数据格式
       console.log('采购趋势原始数据:', this.procurementTrend);
       const procurementData = Array.isArray(this.procurementTrend) ? this.procurementTrend.map(item => item.amount || 0) : (this.procurementTrend.procurementData || []);
       const months = Array.isArray(this.procurementTrend) ? this.procurementTrend.map(item => item.month || '') : (this.procurementTrend.months || []);
       const procurementQuantity = procurementData.map(() => Math.floor(Math.random() * 1000 + 500)); // 模拟采购数量
       
       console.log('处理后的采购数据:', procurementData);
       console.log('处理后的月份数据:', months);
       
       if (procurementData.length === 0) {
         ctx.fillStyle = '#94A3B8';
         ctx.font = '16px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
         ctx.textAlign = 'center';
         ctx.fillText('暂无数据', width / 2, height / 2);
         return;
       }
       
       const maxAmount = Math.max(...procurementData);
       const maxQuantity = Math.max(...procurementQuantity);
       
       // 绘制精致的网格线
       ctx.strokeStyle = '#F1F5F9';
       ctx.lineWidth = 1;
       for (let i = 0; i <= 4; i++) {
         const y = margin.top + (chartHeight / 4) * i;
         ctx.beginPath();
         ctx.moveTo(margin.left, y);
         ctx.lineTo(width - margin.right, y);
         ctx.stroke();
       }
       
       // 绘制Y轴标签 - 更优雅的样式
       for (let i = 0; i <= 4; i++) {
         const y = margin.top + (chartHeight / 4) * i;
         const value = Math.round((maxAmount * (4 - i)) / 4 / 10000) + '万';
         ctx.fillStyle = '#64748B';
         ctx.font = '13px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
         ctx.textAlign = 'right';
         ctx.fillText(value, margin.left - 10, y + 4);
       }
       
       // 绘制采购金额面积填充 - 更优雅的渐变
       const amountGradient = ctx.createLinearGradient(0, margin.top, 0, height - margin.bottom);
       amountGradient.addColorStop(0, 'rgba(6, 182, 212, 0.15)');
       amountGradient.addColorStop(0.6, 'rgba(6, 182, 212, 0.08)');
       amountGradient.addColorStop(1, 'rgba(6, 182, 212, 0.02)');
       
       ctx.fillStyle = amountGradient;
       ctx.beginPath();
       ctx.moveTo(margin.left, height - margin.bottom);
       procurementData.forEach((value, index) => {
         const x = margin.left + (chartWidth / (procurementData.length - 1)) * index;
         const y = height - margin.bottom - (value / maxAmount) * chartHeight;
         ctx.lineTo(x, y);
       });
       ctx.lineTo(width - margin.right, height - margin.bottom);
       ctx.closePath();
       ctx.fill();
       
       // 绘制采购数量面积填充 - 更淡雅的颜色
       const quantityGradient = ctx.createLinearGradient(0, margin.top, 0, height - margin.bottom);
       quantityGradient.addColorStop(0, 'rgba(34, 197, 94, 0.12)');
       quantityGradient.addColorStop(0.6, 'rgba(34, 197, 94, 0.06)');
       quantityGradient.addColorStop(1, 'rgba(34, 197, 94, 0.01)');
       
       ctx.fillStyle = quantityGradient;
       ctx.beginPath();
       ctx.moveTo(margin.left, height - margin.bottom);
       procurementQuantity.forEach((quantity, index) => {
         const x = margin.left + (chartWidth / (procurementQuantity.length - 1)) * index;
         const y = height - margin.bottom - (quantity / maxQuantity) * chartHeight * 0.6;
         if (index === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
       });
       ctx.lineTo(width - margin.right, height - margin.bottom);
       ctx.closePath();
       ctx.fill();
       
       // 绘制采购金额趋势线 - 更精致的样式
       ctx.strokeStyle = '#06B6D4';
       ctx.lineWidth = 3;
       ctx.lineCap = 'round';
       ctx.lineJoin = 'round';
       ctx.beginPath();
       procurementData.forEach((value, index) => {
         const x = margin.left + (chartWidth / (procurementData.length - 1)) * index;
         const y = height - margin.bottom - (value / maxAmount) * chartHeight;
         if (index === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
       });
       ctx.stroke();
       
       // 绘制采购数量趋势线 - 更精致的样式
       ctx.shadowColor = 'rgba(34, 197, 94, 0.35)';
       ctx.shadowBlur = 12;
       ctx.shadowOffsetY = 2;
       ctx.strokeStyle = '#22C55E';
       ctx.lineWidth = 2.5;
       ctx.lineCap = 'round';
       ctx.lineJoin = 'round';
       ctx.beginPath();
       procurementQuantity.forEach((quantity, index) => {
         const x = margin.left + (chartWidth / (procurementQuantity.length - 1)) * index;
         const y = height - margin.bottom - (quantity / maxQuantity) * chartHeight * 0.6;
         if (index === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
       });
       ctx.stroke();
       
       // 重置阴影
       ctx.shadowColor = 'transparent';
       ctx.shadowBlur = 0;
       ctx.shadowOffsetY = 0;
       
       // 绘制采购金额数据点 - 精致的多层次设计
       procurementData.forEach((value, index) => {
         const x = margin.left + (chartWidth / (procurementData.length - 1)) * index;
         const y = height - margin.bottom - (value / maxAmount) * chartHeight;
         
         // 外圈阴影
         ctx.shadowColor = 'rgba(20, 184, 166, 0.3)';
         ctx.shadowBlur = 12;
         ctx.shadowOffsetY = 2;
         ctx.fillStyle = '#FFFFFF';
         ctx.strokeStyle = 'rgba(20, 184, 166, 0.2)';
         ctx.lineWidth = 2;
         ctx.beginPath();
         ctx.arc(x, y, 7, 0, 2 * Math.PI);
         ctx.fill();
         ctx.stroke();
         
         // 内圈
         ctx.shadowColor = 'transparent';
         ctx.shadowBlur = 0;
         ctx.shadowOffsetY = 0;
         ctx.fillStyle = '#14B8A6';
         ctx.beginPath();
         ctx.arc(x, y, 4.5, 0, 2 * Math.PI);
         ctx.fill();
       });
       
       // 绘制采购数量数据点 - 精致的多层次设计
       procurementQuantity.forEach((quantity, index) => {
         const x = margin.left + (chartWidth / (procurementQuantity.length - 1)) * index;
         const y = height - margin.bottom - (quantity / maxQuantity) * chartHeight * 0.6;
         
         // 外圈阴影
         ctx.shadowColor = 'rgba(34, 197, 94, 0.3)';
         ctx.shadowBlur = 10;
         ctx.shadowOffsetY = 2;
         ctx.fillStyle = '#FFFFFF';
         ctx.strokeStyle = 'rgba(34, 197, 94, 0.2)';
         ctx.lineWidth = 1.5;
         ctx.beginPath();
         ctx.arc(x, y, 6, 0, 2 * Math.PI);
         ctx.fill();
         ctx.stroke();
         
         // 内圈
         ctx.shadowColor = 'transparent';
         ctx.shadowBlur = 0;
         ctx.shadowOffsetY = 0;
         ctx.fillStyle = '#22C55E';
         ctx.beginPath();
         ctx.arc(x, y, 3.8, 0, 2 * Math.PI);
         ctx.fill();
       });
       
       // 绘制月份标签 - 优化字体和位置
       months.forEach((month, index) => {
         if (month) {
           const x = margin.left + (chartWidth / (months.length - 1)) * index;
           ctx.fillStyle = '#64748B';
           ctx.font = '12px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif';
           ctx.textAlign = 'center';
           ctx.fillText(month, x, height - margin.bottom + 18);
         }
       });
     },
    drawQualityChart() {
       const canvas = this.$refs.qualityChart;
       if (!canvas) return;
       const ctx = canvas.getContext('2d');
       const width = canvas.width;
       const height = canvas.height;
       
       ctx.clearRect(0, 0, width, height);
       
       console.log('绘制质量趋势图表，数据:', this.qualityTrend);
       
       // 处理数据格式 - 将合格率转换为不合格数量
       console.log('质量趋势原始数据:', this.qualityTrend);
       const qualityRates = Array.isArray(this.qualityTrend) ? this.qualityTrend.map(item => item.rate || 0) : (this.qualityTrend.qualityRates || []);
       const months = Array.isArray(this.qualityTrend) ? this.qualityTrend.map(item => item.month || '') : (this.qualityTrend.months || []);
       const defectiveQuantities = qualityRates.map(rate => Math.floor((100 - rate) * 10 + Math.random() * 50)); // 模拟不合格数量
       
       console.log('处理后的质量数据:', qualityRates);
       console.log('处理后的月份数据:', months);
       console.log('处理后的不合格数量:', defectiveQuantities);
       
       if (defectiveQuantities.length === 0) {
         ctx.fillStyle = '#94A3B8';
         ctx.font = '14px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif';
         ctx.textAlign = 'center';
         ctx.fillText('暂无数据', width / 2, height / 2);
         return;
       }
       
       // 定义图表边距
       const margin = { top: 20, right: 20, bottom: 40, left: 50 };
       const chartWidth = width - margin.left - margin.right;
       const chartHeight = height - margin.top - margin.bottom;
       
       // 绘制网格线和Y轴标签 - 更精致的样式
       ctx.strokeStyle = 'rgba(226, 232, 240, 0.6)';
       ctx.lineWidth = 0.8;
       for (let i = 0; i <= 4; i++) {
         const y = margin.top + (chartHeight / 4) * i;
         ctx.beginPath();
         ctx.moveTo(margin.left, y);
         ctx.lineTo(margin.left + chartWidth, y);
         ctx.stroke();
         
         // 绘制Y轴标签 - 优化字体和位置
         if (i < 4) {
           const value = (100 - i * 25) + '万';
           ctx.fillStyle = '#64748B';
           ctx.font = '12px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif';
           ctx.textAlign = 'right';
           ctx.fillText(value, margin.left - 8, y + 4);
         }
       }
       
       const maxDefective = Math.max(...defectiveQuantities);
       
       // 绘制不合格数量面积填充 - 精致的多层次渐变
       const defectiveGradient = ctx.createLinearGradient(0, margin.top, 0, margin.top + chartHeight);
       defectiveGradient.addColorStop(0, 'rgba(239, 68, 68, 0.25)');
       defectiveGradient.addColorStop(0.3, 'rgba(239, 68, 68, 0.15)');
       defectiveGradient.addColorStop(0.6, 'rgba(239, 68, 68, 0.08)');
       defectiveGradient.addColorStop(0.85, 'rgba(239, 68, 68, 0.03)');
       defectiveGradient.addColorStop(1, 'rgba(239, 68, 68, 0.01)');
       
       ctx.fillStyle = defectiveGradient;
       ctx.beginPath();
       ctx.moveTo(margin.left, margin.top + chartHeight);
       defectiveQuantities.forEach((quantity, index) => {
         const x = margin.left + (chartWidth / (defectiveQuantities.length - 1)) * index;
         const y = margin.top + chartHeight - (quantity / maxDefective) * chartHeight;
         ctx.lineTo(x, y);
       });
       ctx.lineTo(margin.left + chartWidth, margin.top + chartHeight);
       ctx.closePath();
       ctx.fill();
       
       // 绘制不合格数量趋势线 - 精致的阴影效果
       ctx.shadowColor = 'rgba(239, 68, 68, 0.35)';
       ctx.shadowBlur = 12;
       ctx.shadowOffsetY = 2;
       ctx.strokeStyle = '#EF4444';
       ctx.lineWidth = 3;
       ctx.lineCap = 'round';
       ctx.lineJoin = 'round';
       ctx.beginPath();
       defectiveQuantities.forEach((quantity, index) => {
         const x = margin.left + (chartWidth / (defectiveQuantities.length - 1)) * index;
         const y = margin.top + chartHeight - (quantity / maxDefective) * chartHeight;
         if (index === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
       });
       ctx.stroke();
       
       // 重置阴影
       ctx.shadowColor = 'transparent';
       ctx.shadowBlur = 0;
       ctx.shadowOffsetY = 0;
       
       // 绘制数据点 - 精致的多层次设计
       defectiveQuantities.forEach((quantity, index) => {
         const x = margin.left + (chartWidth / (defectiveQuantities.length - 1)) * index;
         const y = margin.top + chartHeight - (quantity / maxDefective) * chartHeight;
         
         // 外圈阴影
         ctx.shadowColor = 'rgba(239, 68, 68, 0.4)';
         ctx.shadowBlur = 14;
         ctx.shadowOffsetY = 3;
         ctx.fillStyle = '#FFFFFF';
         ctx.strokeStyle = 'rgba(239, 68, 68, 0.2)';
         ctx.lineWidth = 2;
         ctx.beginPath();
         ctx.arc(x, y, 8, 0, 2 * Math.PI);
         ctx.fill();
         ctx.stroke();
         
         // 中圈
         ctx.shadowColor = 'transparent';
         ctx.shadowBlur = 0;
         ctx.shadowOffsetY = 0;
         ctx.fillStyle = '#FEE2E2';
         ctx.beginPath();
         ctx.arc(x, y, 5.5, 0, 2 * Math.PI);
         ctx.fill();
         
         // 内圈
         ctx.fillStyle = '#EF4444';
         ctx.beginPath();
         ctx.arc(x, y, 3.5, 0, 2 * Math.PI);
         ctx.fill();
       });
       
       // 绘制月份标签 - 优化字体和位置
       months.forEach((month, index) => {
         if (month) {
           const x = margin.left + (chartWidth / (months.length - 1)) * index;
           ctx.fillStyle = '#64748B';
           ctx.font = '12px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif';
           ctx.textAlign = 'center';
           ctx.fillText(month, x, height - margin.bottom + 18);
         }
       });
     }
  }
}
</script>

<style scoped>
.main-content-wrapper {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
.stats-cards{display:grid;grid-template-columns:repeat(6,1fr);gap:20px;margin-bottom:30px}.stats-card{background:white;border-radius:8px;padding:20px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 4px rgba(0,0,0,.1);color:white}.stats-card-blue{background:linear-gradient(135deg,#42A5F5,#1E88E5)}.stats-card-green{background:linear-gradient(135deg,#66BB6A,#43A047)}.stats-card-blue-2{background:linear-gradient(135deg,#26C6DA,#00ACC1)}.stats-card-red{background:linear-gradient(135deg,#EF5350,#E53935)}.stats-card-yellow{background:linear-gradient(135deg,#FFCA28,#FFA000)}.stats-card-purple{background:linear-gradient(135deg,#AB47BC,#8E24AA)}.stats-content{flex:1}.stats-title{font-size:14px;opacity:.9;margin-bottom:5px}.stats-value{font-size:20px;font-weight:700;margin-bottom:5px}.stats-growth{font-size:12px;opacity:.8}.stats-growth.positive{color:#4CAF50}.stats-icon{font-size:24px;opacity:.8}.charts-section{margin-bottom:30px}.chart-row{display:grid;grid-template-columns:2fr 1fr;gap:20px;margin-bottom:20px}.chart-row:last-child{grid-template-columns:1fr 1fr 1fr}.chart-container{background:white;border-radius:12px;padding:24px;box-shadow:0 4px 20px rgba(0,0,0,.08);border:1px solid rgba(0,0,0,.05);transition:all 0.3s ease}.chart-container:hover{box-shadow:0 8px 30px rgba(0,0,0,.12);transform:translateY(-2px)}.chart-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:10px;border-bottom:1px solid #f0f0f0}.chart-header h3{margin:0;font-size:16px;color:#333}.chart-legend{display:flex;gap:20px}.legend-item{display:flex;align-items:center;font-size:12px;color:#666}.legend-color{width:12px;height:12px;border-radius:2px;margin-right:5px}.legend-purple{background:#6366F1}.legend-blue{background:#14B8A6}.legend-light-blue{background:#22C55E}.legend-red{background:#EF4444}.chart-content{height:200px;position:relative}.pie-chart{display:flex;align-items:center;gap:20px}.pie-legend{flex:1}.pie-legend-item{display:flex;align-items:center;gap:10px;margin-bottom:10px}.pie-color{width:12px;height:12px;border-radius:50%}.pie-color-1{background:#4CAF50}.stats-table .chart-content{height:auto}.stats-list{margin-top:10px}.stats-row{display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid #f0f0f0}.stats-row:last-child{border-bottom:none}.stats-label{color:#666;font-size:14px}.stats-number{font-weight:700;color:#333}.stats-percent{color:#666;font-size:12px}.table-section{background:white;border-radius:8px;padding:20px;box-shadow:0 2px 4px rgba(0,0,0,.1)}.table-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:15px;border-bottom:1px solid #f0f0f0}.table-header h3{margin:0;font-size:16px;color:#333}.table-controls{display:flex;gap:10px;align-items:center}.table-select,.table-search{padding:8px 12px;border:1px solid #ddd;border-radius:4px;font-size:14px}.table-search{width:200px}.search-btn{background:#2196F3;color:white;border:none;padding:8px 16px;border-radius:4px;cursor:pointer}.reset-btn{background:#f5f5f5;color:#666;border:1px solid #ddd;padding:8px 16px;border-radius:4px;cursor:pointer}.table-container{overflow-x:auto;margin-bottom:20px;border:1px solid #e0e0e0;border-radius:4px}.data-table{width:max-content;min-width:100%;border-collapse:collapse;white-space:nowrap}.data-table th,.data-table td{padding:12px 16px;text-align:left;border-bottom:1px solid #f0f0f0;min-width:120px}.data-table th:first-child,.data-table td:first-child{min-width:60px}.data-table th:nth-child(2),.data-table td:nth-child(2){min-width:150px}.data-table th:nth-child(3),.data-table td:nth-child(3){min-width:100px}.data-table th:nth-child(4),.data-table td:nth-child(4){min-width:140px}.data-table th:nth-child(5),.data-table td:nth-child(5){min-width:100px}.data-table th:nth-child(6),.data-table td:nth-child(6){min-width:120px}.data-table th:nth-child(7),.data-table td:nth-child(7){min-width:140px}.data-table th:nth-child(8),.data-table td:nth-child(8){min-width:100px}.data-table th:nth-child(9),.data-table td:nth-child(9){min-width:100px}.data-table th:nth-child(10),.data-table td:nth-child(10){min-width:100px}.data-table th:nth-child(11),.data-table td:nth-child(11){min-width:120px}.data-table th:nth-child(12),.data-table td:nth-child(12){min-width:120px}.data-table th:nth-child(13),.data-table td:nth-child(13){min-width:120px}.data-table th:nth-child(14),.data-table td:nth-child(14){min-width:120px}.data-table th:nth-child(15),.data-table td:nth-child(15){min-width:120px}.data-table th{background:#f8f9fa;font-weight:500;color:#333}.status-tag{padding:4px 8px;border-radius:12px;font-size:12px;font-weight:500}.status-green{background:#e8f5e8;color:#4caf50}.status-orange{background:#fff3e0;color:#ff9800}.status-red{background:#ffebee;color:#f44336}.status-gray{background:#f5f5f5;color:#666}.status-badge{padding:4px 8px;border-radius:12px;font-size:12px;font-weight:500;display:inline-block}.status-pending{background:#e8f5e8;color:#4caf50}.status-partial{background:#fff3e0;color:#ff9800}.status-shipped{background:#ffebee;color:#f44336}.status-completed{background:#f5f5f5;color:#666}.status-default{background:#f5f5f5;color:#666}.table-pagination{display:flex;justify-content:space-between;align-items:center}.pagination-controls{display:flex;gap:5px;align-items:center}.page-btn{padding:8px 12px;border:1px solid #ddd;background:white;cursor:pointer;border-radius:4px;font-size:14px;transition:all 0.2s ease}.page-btn:hover{background:#f5f5f5;border-color:#2196F3}.page-btn.active{background:#2196F3;color:white;border-color:#2196F3}.page-btn.disabled{background:#f5f5f5;color:#ccc;cursor:not-allowed;border-color:#e0e0e0}.page-btn.disabled:hover{background:#f5f5f5;border-color:#e0e0e0}.pagination-info{color:#666;font-size:14px}
</style>
